import cv2
import numpy as np
from PIL import Image

def imageMerge(img_1, img_2, flag='y'):
    img1 = Image.fromarray(cv2.cvtColor(img_1, cv2.COLOR_BGR2RGB))
    img2 = Image.fromarray(cv2.cvtColor(img_2, cv2.COLOR_BGR2RGB))
    size1, size2 = img1.size, img2.size
    if flag == 'x':
        joint = Image.new("RGB", (size1[0] + size2[0], size1[1]))
        loc1, loc2 = (0, 0), (size1[0], 0)
    else:
        joint = Image.new("RGB", (size1[0], size2[1]+size1[1]))
        loc1, loc2 = (0, 0), (0, size1[1])
    joint.paste(img1, loc1)
    joint.paste(img2, loc2)
    # joint.save('joint.png')
    return cv2.cvtColor(np.asarray(joint), cv2.COLOR_RGB2BGR)

filename = r'E:\labelAnnotation\Screenshots\WoWScrnShot_080122_151748.jpg'
image = cv2.imread(filename, 1)
#二值化
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
binary = cv2.adaptiveThreshold(~gray, 255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 15, -10)
# cv2.imshow("cell", binary)
# cv2.waitKey(0)
rows,cols=binary.shape
scale = 20
#识别横线
kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(cols//scale,1))
eroded = cv2.erode(binary,kernel,iterations = 1)
#cv2.imshow("Eroded Image",eroded)
dilatedcol = cv2.dilate(eroded,kernel,iterations = 1)
# 接着我们用连通域来数线的根数
# 阈值分割得到二值化图片
ret, binary = cv2.threshold(dilatedcol, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
# 膨胀操作
kernel2 = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
bin_clo = cv2.dilate(binary, kernel2, iterations=2)
# 连通域分析
num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(bin_clo, connectivity=8)
# 查看各个返回值
# 连通域数量
print('num_labels = ',num_labels)
# 连通域的信息：对应各个轮廓的x、y、width、height和面积
print('stats = ',stats)
# 连通域的中心点
print('centroids = ',centroids)
# 每一个像素的标签1、2、3.。。，同一个连通域的标签是一致的
print('labels = ',labels)

# 不同的连通域赋予不同的颜色
output = np.zeros((gray.shape[0], gray.shape[1], 3), np.uint8)
for i in range(1, num_labels):

    mask = labels == i
    output[:, :, 0][mask] = np.random.randint(0, 255)
    output[:, :, 1][mask] = np.random.randint(0, 255)
    output[:, :, 2][mask] = np.random.randint(0, 255)
# cv2.imshow('oginal', output)
# cv2.waitKey()
# cv2.destroyAllWindows()

all1 = imageMerge(image,dilatedcol,'x')
all2 = imageMerge(all1,output,'y')

# cv2.imshow("Dilated Image",all1)
# cv2.waitKey(0)
#识别竖线
kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(1,rows//scale))
eroded = cv2.erode(binary,kernel,iterations = 1)
dilatedrow = cv2.dilate(eroded,kernel,iterations = 1)
all3 = imageMerge(all2,dilatedrow,'x')
#标识交点
bitwiseAnd = cv2.bitwise_and(dilatedcol,dilatedrow)
# cv2.imshow("Dilated Image",bitwiseAnd)
# cv2.waitKey(0)
# cv2.imshow("bitwiseAnd Image",bitwiseAnd)
# cv2.waitKey(0)
#标识表格
merge = cv2.add(dilatedcol,dilatedrow)
all4 = imageMerge(all3,merge,'y')
cv2.imwrite('yehaiboBest.jpg',all4)
# all2 = imageMerge(image,merge,'x')
# cv2.imwrite('yehaibo3.jpg',all2)
# cv2.imshow("add Image",merge)
# cv2.waitKey(0)